package com.jiyongjun.bms.base.configurer;

import com.jiyongjun.bms.tool.exception.BizException;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * description: 全局异常处理器
 * <p>
 * 可以定义多个异常处理器，一个异常只会被最精确匹配的异常处理器处理
 *
 * @author yongjun.ji
 * @date 2019/2/2 16:26
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception e, WebRequest request, HttpServletRequest servletRequest) {
        StringWriter sw = new StringWriter();
        PrintWriter ps = new PrintWriter(sw);
        e.printStackTrace(ps);
        ModelAndView error = new ModelAndView("error");
        // 参照BasicErrorHandler的属性
        error.addObject("message", e.getMessage());
        error.addObject("exception", e.getClass().getName());
        error.addObject("trace", sw.toString());
        return error;
    }

    @ExceptionHandler(value = BizException.class)
    public void bizException(BizException e, WebRequest request, HttpServletRequest servletRequest) {
        request.setAttribute("message", e.getMessage(), 0);
        servletRequest.setAttribute("message", e.getMessage());
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("msg", "额外信息");
        model.addAttribute("homeUrl", "http://localhost:80");
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        // 可以屏蔽id字段传值
        // webDataBinder.setDisallowedFields("id");
    }

}
